<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <!--          <el-form-item label="用户账号" prop="userName">-->
          <!--            <el-input v-model="queryParams.userName" placeholder="请输入用户账号" clearable style="width: 240px"-->
          <!--                      @keyup.enter="handleQuery"/>-->
          <!--          </el-form-item>-->
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model="queryParams.nickName" placeholder="请输入用户昵称" clearable style="width: 240px"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable style="width: 240px"
                      @keyup.enter="handleQuery"/>
          </el-form-item>

          <!--          <el-form-item label="余额" prop="amount">-->
          <!--            <el-input v-model="queryParams.amount" placeholder="请输入余额" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="线下代理" prop="vip">-->
          <!--            <el-select v-model="queryParams.xianxia" placeholder="请选择线下代理" clearable @change="handleQuery">-->
          <!--              <el-option-->
          <!--                v-for="dict in xianxia"-->
          <!--                :key="dict.value"-->
          <!--                :label="dict.label"-->
          <!--                :value="dict.value"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <el-form-item label="用户类型" prop="isWaiter">
            <el-select v-model="queryParams.isWaiter" placeholder="请选择用户类型" clearable @change="handleQuery">
              <el-option
                v-for="dict in is_waiter"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="会员等级" prop="vip">
            <el-select v-model="queryParams.vip" placeholder="请选择会员等级" clearable @change="handleQuery">
              <el-option
                v-for="dict in vipList"
                :key="dict.businessConfigId"
                :label="dict.configName"
                :value="dict.sortNo"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="打手等级" prop="dsVip">
            <el-select v-model="queryParams.dsVip" placeholder="请选择打手等级" clearable @change="handleQuery">
              <el-option
                v-for="dict in dsVipList"
                :key="dict.businessConfigId"
                :label="dict.configName"
                :value="dict.businessConfigId"
              />
            </el-select>
          </el-form-item>
          <!--          <el-form-item label="上级ID" prop="superiorId">-->
          <!--            <el-input v-model="queryParams.superiorId" placeholder="请输入上级ID" clearable style="width: 240px"-->
          <!--                      @keyup.enter="handleQuery"/>-->
          <!--          </el-form-item>-->
          <el-form-item label="用户ID" prop="userId">
            <el-input v-model="queryParams.userId" placeholder="请输入用户ID" clearable style="width: 240px"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <!--          <el-form-item label="自己业绩" prop="performance">-->
          <!--            <el-input v-model="queryParams.performance" placeholder="请输入自己业绩" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="自购金额" prop="buyAmount">-->
          <!--            <el-input v-model="queryParams.buyAmount" placeholder="请输入自购金额" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
          <!--          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['business:businessUser:add']">新增</el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['business:businessUser:edit']">修改</el-button>-->
          <!--          </el-col>-->
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                       v-hasPermi="['business:businessUser:remove']">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
                       v-hasPermi="['business:businessUser:export']">导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="businessUserList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="用户ID" align="center" prop="userId" v-if="true"/>
        <!--        <el-table-column label="用户账号" align="center" prop="userName"/>-->
        <el-table-column label="微信头像" align="center" prop="wxAvatar" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.avatar" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="用户昵称" align="center" prop="nickName"/>
        <el-table-column label="帐号状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="微信绑定手机号码" align="center" prop="phonenumber"/>
        <!--        <el-table-column label="用户性别" align="center" prop="sex" />-->
        <!--        <el-table-column label="头像地址" align="center" prop="avatar" />-->
        <!--        <el-table-column label="密码" align="center" prop="password" />-->
        <el-table-column label="余额" align="center" prop="amount"/>
        <el-table-column label="会员等级" align="center" prop="vip" :formatter="formatVip"/>
        <el-table-column label="用户类型" align="center" prop="isWaiter">
          <template #default="scope">
            <dict-tag :options="is_waiter" :value="scope.row.isWaiter"/>
          </template>
        </el-table-column>

        <el-table-column label="消费金额" align="center" prop="allAmount"/>

        <el-table-column label="总订单数量" align="center" prop="allOrder"/>
        <el-table-column label="今日收入" align="center" prop="dayAmount"/>
        <el-table-column label="本周收入" align="center" prop="weekAmount"/>
        <el-table-column label="本月收入" align="center" prop="monthAmount"/>

        <el-table-column label="打手提成" align="center" prop="reward"/>
        <el-table-column label="游戏马甲" align="center" prop="gameName"/>
        <el-table-column label="打手等级" align="center" prop="dsVip" :formatter="formatDsVip"/>
        <el-table-column label="延迟时间" align="center" prop="delayTime"/>
        <el-table-column label="姓名" align="center" prop="relName"/>
        <el-table-column label="手机" align="center" prop="phone"/>
        <el-table-column label="性别" align="center" prop="sex">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.sex"/>
          </template>
        </el-table-column>
        <el-table-column label="入驻游戏" align="center" prop="gameId"/>
        <!--        <el-table-column label="入驻游戏" align="center" prop="gameId"/>-->
        <el-table-column label="游戏区服" align="center" prop="gameArea">
          <template #default="scope">
            <dict-tag :options="game_area" :value="scope.row.gameArea"/>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="评论" placement="top" v-if="scope.row.isWaiter == 1">
              <el-button link type="primary" icon="ChatLineRound" @click="goInfo(scope.row.userId)"
                         v-hasPermi="['business:watch:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="流水" placement="top">
              <el-button link type="primary" icon="MessageBox" @click="openFlow(scope.row.userId)"
                         v-hasPermi="['business:businessUser:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="充值" placement="top">
              <el-button link type="primary" icon="Iphone" @click="openGive(scope.row.userId)"
                         v-hasPermi="['business:businessUser:edit']"></el-button>
            </el-tooltip>
            <!--            <el-tooltip content="关系图" placement="top">-->
            <!--              <el-button link type="primary" icon="Fold" @click="goRelation(scope.row.userId)"-->
            <!--                         v-hasPermi="['business:businessUser:edit']"></el-button>-->
            <!--            </el-tooltip>-->
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['business:businessUser:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['business:businessUser:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改用户信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="30%" append-to-body>
      <el-form ref="businessUserFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入用户昵称"/>
        </el-form-item>
        <!--        <el-form-item label="用户邮箱" prop="email">-->
        <!--          <el-input v-model="form.email" placeholder="请输入用户邮箱" />-->
        <!--        </el-form-item>-->
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号码"/>
        </el-form-item>
        <!--        <el-form-item label="余额" prop="amount">-->
        <!--          <el-input v-model="form.amount" placeholder="请输入余额"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="会员等级" prop="vip">
          <el-radio-group v-model="form.vip">
            <el-radio
              v-for="dict in vipList"
              :key="dict.businessConfigId"
              :label="dict.sortNo"
            >{{ dict.configName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户类型" prop="isWaiter">
          <el-radio-group v-model="form.isWaiter">
            <el-radio
              v-for="dict in is_waiter"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!--        <el-form-item label="上级id" prop="superiorId">-->
        <!--          <el-input v-model="form.superiorId" placeholder="请输入上级"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="服务项目" prop="typeIds" v-if="form.isWaiter == 1">
          <el-select
            v-model="form.typeListIds"
            multiple
            placeholder="请选择可服务项目"
            style="width: 360px"
          >
            <el-option
              v-for="item in oneTypeList"
              :key="item.businessConfigId"
              :label="item.configName"
              :value="item.businessConfigId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="打手提成" prop="reward" v-if="form.isWaiter == 1">
          <el-input v-model="form.reward" type="number" placeholder="请输入打手提成,例: 0.7 即70%提成"/>
        </el-form-item>
        <el-form-item label="打手等级" prop="reward" v-if="form.isWaiter == 1">
          <el-radio-group v-model="form.dsVip">
            <el-radio
              v-for="dict in dsVipList"
              :key="dict.businessConfigId"
              :label="dict.businessConfigId"
            >{{ dict.configName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="延迟时间" prop="reward" v-if="form.isWaiter == 1">
          <el-input v-model="form.delayTime" type="number" placeholder="请输入接单延迟时间 单位秒"/>
        </el-form-item>
        <el-form-item label="打手简介" prop="info" v-if="form.isWaiter == 1">
          <el-input v-model="form.info" type="textarea" placeholder="请输入打手简介"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 流水对话框 -->
    <el-dialog title="用户流水" v-model="flowDialog" width="50%" append-to-body>
      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="flowQueryParams.flowingType" @change="getFlowList">
          <el-radio
            v-for="dict in flowing_max"
            :key="dict.value"
            :label="dict.value"
          >{{dict.label}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-table v-loading="loading" :data="flowList">
        <el-table-column label="余额" align="center" prop="amount"/>
        <el-table-column label="流水类型" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="flowing_type" :value="scope.row.type"/>
          </template>
        </el-table-column>
        <el-table-column label="编号" align="center" prop="subordinateId"/>
        <el-table-column label="备注" align="center" prop="subordinate"/>
        <el-table-column label="时间" align="center" prop="createTime"/>
      </el-table>
      <pagination
        v-show="flowTotal>0"
        :total="flowTotal"
        v-model:page="flowQueryParams.pageNum"
        v-model:limit="flowQueryParams.pageSize"
        @pagination="getFlowList"
      />
    </el-dialog>
    <!-- 充值对话框 -->
    <el-dialog title="充值" v-model="giveDialog" width="30%" append-to-body>
      <el-form ref="businessUserFormRef" :model="giveParams" label-width="80px">
        <el-form-item label="充值类型" prop="vipStatus">
          <el-radio-group v-model="giveParams.type">
            <el-radio
              v-for="dict in flowing_max"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input v-model="giveParams.amount" placeholder="请输入金额" type="number"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitGiveForm">确 定</el-button>
          <el-button @click="giveDialog = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BusinessUser" lang="ts">
import {
  listBusinessUser,
  getBusinessUser,
  delBusinessUser,
  addBusinessUser,
  updateBusinessUser,
  giveApi
} from '@/api/business/businessUser';
import {getByKeyApi} from '@/api/business/config';
import {BusinessUserVO, BusinessUserQuery, BusinessUserForm} from '@/api/business/businessUser/types';
import {listFlowing, getFlowing, delFlowing, addFlowing, updateFlowing} from '@/api/business/flowing';
import {FlowingVO, FlowingQuery, FlowingForm} from '@/api/business/flowing/types';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {
  flowing_type,
  flowing_max,
  is_waiter,
  sys_normal_disable,
  game_area,
  sys_user_sex
} = toRefs<any>(proxy?.useDict('flowing_type', 'flowing_max', 'is_waiter', 'sys_normal_disable', 'game_area', 'sys_user_sex'));

const businessUserList = ref<BusinessUserVO[]>([]);
const flowList = ref<any[]>([]);
const vipList = ref([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const flowDialog = ref(false);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const flowTotal = ref(0);

const queryFormRef = ref<ElFormInstance>();
const businessUserFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: BusinessUserForm = {
  userId: undefined,
  deptId: undefined,
  userName: undefined,
  nickName: undefined,
  userType: undefined,
  email: undefined,
  phonenumber: undefined,
  openid: undefined,
  unionid: undefined,
  sex: undefined,
  avatar: undefined,
  password: undefined,
  amount: undefined,
  vip: undefined,
  status: undefined,
  loginIp: undefined,
  loginDate: undefined,
  remark: undefined,
  qrCode: undefined,
  superiorId: undefined,
  wxAvatar: undefined,
  performance: undefined,
  buyAmount: undefined,
  isWaiter: undefined
}
const data = reactive<PageData<BusinessUserForm, BusinessUserQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    userType: undefined,
    email: undefined,
    phonenumber: undefined,
    openid: undefined,
    unionid: undefined,
    sex: undefined,
    avatar: undefined,
    password: undefined,
    amount: undefined,
    vip: undefined,
    status: undefined,
    loginIp: undefined,
    loginDate: undefined,
    qrCode: undefined,
    superiorId: undefined,
    wxAvatar: undefined,
    performance: undefined,
    buyAmount: undefined,
    params: {}
  },
  rules: {
    userId: [
      {required: true, message: "用户ID不能为空", trigger: "blur"}
    ],
    nickName: [
      {required: true, message: "用户昵称不能为空", trigger: "blur"}
    ],
    vip: [
      {required: true, message: "vip等级", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);
// const {flowQueryParams} = toRefs(data);
const flowData = reactive<any>({
  flowQueryParams: {
    pageNum: 1,
    pageSize: 10,
    createBy: null,
    flowingType: null,
  }
})
const {flowQueryParams} = toRefs(flowData);
/** 查询用户信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listBusinessUser(queryParams.value);
  businessUserList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}
/** 查询用户信息列表 */
const getFlowList = async () => {
  // loading.value = true;
  const res = await listFlowing(flowQueryParams.value);
  flowList.value = res.rows;
  flowTotal.value = res.total;
  // loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}
const getByKey = async () => {
  const res = await getByKeyApi('vip');
  vipList.value = res.data;
};
const formatVip = (row: BusinessUserVO, column: any) => {
  return vipList.value.find((item: any) => item.sortNo == row.vip)?.configName;
};

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  businessUserFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: BusinessUserVO[]) => {
  ids.value = selection.map(item => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加用户信息";
}

/** 新增按钮操作 */
const openFlow = (userId) => {
  flowQueryParams.value.createBy = userId;
  getFlowList();
  flowDialog.value = true;
}


/** 修改按钮操作 */
const handleUpdate = async (row?: BusinessUserVO) => {
  reset();
  const _userId = row?.userId || ids.value[0]
  const res = await getBusinessUser(_userId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改用户信息";
}

/** 提交按钮 */
const submitForm = () => {
  businessUserFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.userId) {
        await updateBusinessUser(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addBusinessUser(form.value).finally(() => buttonLoading.value = false);
      }
      await proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: BusinessUserVO) => {
  const _userIds = row?.userId || ids.value;
  await proxy?.$modal.confirm('是否确认删除用户信息编号为"' + _userIds + '"的数据项？').finally(() => loading.value = false);
  await delBusinessUser(_userIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('business/businessUser/export', {
    ...queryParams.value
  }, `businessUser_${new Date().getTime()}.xlsx`)
}

const giveData = reactive<any>({
  giveParams: {
    userId: "",
    amount: "",
    type: "1",
  }
})

const openGive = (userId) => {
  giveParams.value.userId = userId;
  giveDialog.value = true;
}
const {giveParams} = toRefs(giveData);
const giveDialog = ref(false);
const submitGiveForm = async () => {
  await giveApi(giveParams.value).finally(() => buttonLoading.value = false);
  giveDialog.value = false;
  await getList();
}


const router = useRouter();
const goRelation = async (userId: string) => {
  router.push({path: 'relation', query: {userId}})
}

const oneTypeList = ref([]);
const getOneTypeList = async () => {
  const res = await getByKeyApi("goods_type");
  oneTypeList.value = res.data;
};

const goInfo = async (waiterId: string) => {
  router.push({path: 'post', query: {waiterId}})
}

const dsVipList = ref([]);
const getDsVip = async () => {
  const res = await getByKeyApi('dsVip');
  dsVipList.value = res.data;
};
const formatDsVip = (row: BusinessUserVO, column: any) => {
  return dsVipList.value.find((item: any) => item.businessConfigId == row.dsVip)?.configName;
};
onMounted(() => {
  getList();
  getByKey();
  getDsVip();
  getOneTypeList();
});
</script>
